import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;

public class TurnHandler {

	private int number;

	private Map world;

	private boolean turnOver;

	private boolean print;

	private boolean manual;

	public TurnHandler(Map w, boolean prnt, boolean man) {
		turnOver = true;
		number = 0;
		world = w;
		print = prnt;
		setManual(man);
	}

	public void handle() {
		@SuppressWarnings("resource")
		Scanner s = new Scanner(System.in);
		while (true) {
			if (isGameOver()) {
				Main.quit();
			}
			if (print) {
				world.printMap();
			}
			if (isManual()) {
				String es = s.nextLine();
				if (es.equals("quit")) {
					Main.quit();
				}
			} else {
				try {
					Thread.sleep(Main.getWaitTime());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			if (turnOver) {
				nextTurn();
			}
		}

	}

	public void nextTurn() {
		turnOver = false;
		Main.getMap().weaken();
		int rand = (int) (Math.random() * 2);
//		if (rand > 1) {
//			world.getAggressor().makeMove();
//			world.getBrain().makeMove();
//		} else {
//			world.getBrain().makeMove();
//			world.getAggressor().makeMove();
//		}
		Iterator it = Main.getMap().getAgents().iterator();
		while(it.hasNext()) {
			Agent agent = (Agent) it.next();

			if(agent.getEnergy() < 1)
			{

				Main.getMap().getMap()[agent.getPosition().y][agent.getPosition().x] = new BlankSpace(agent.getPosition());
				it.remove();
				
			}
		
		
			if(agent.isAlive())
				agent.makeMove();
		}
		
		Iterator it2 = Main.getMap().getAgents().iterator();
		while(it2.hasNext()) {
			Agent agent = (Agent) it2.next();
			if(!agent.isAlive())
				it2.remove();
		}
		
		number++;
		turnOver = true;
	}

	public int getNumber() {
		return number;
	}

	private boolean isGameOver() {
		if (Main.getMap().getAgents().size() < 1) {
			return true;
		}
//		Foundry f = Main.getWorld().getFoundry();
//		if (b.getRedCells().size() < 1 && b.getWhiteCells().size() < 1
//				&& !f.hasOxygen()) {
//			return true;
//		}

		return false;
	}

	public boolean isManual() {
		return manual;
	}

	public void setManual(boolean manual) {
		this.manual = manual;
	}

}
